package com.cakebackoffice;


import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
import com.cakebackoffice.Model.Order;
import com.cakebackoffice.Model.OrderLine;

import java.util.List;

public class OrderSheetActivity extends Activity {

    private long currentIdOrder;
    private Order currentOrder;
    private boolean flagOrder = false;

    static final int CHANGE_PHONE_DIALOG = 0;
    static final int CHANGE_NAME_DIALOG = 1;
    static final int CHANGE_ADRESS_DIALOG = 2;
    private List<OrderLine> printedOrderLines;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);    //To change body of overridden methods use File | Settings | File Templates.
        setContentView(R.layout.ordersheet);
        Intent intent = getIntent();


        currentIdOrder = intent.getExtras().getInt("orderIdDB");

        this.currentOrder = Order.getOne(this, this.currentIdOrder);
        this.setContentView();


        ListView listView = (ListView) findViewById(R.id.listViewOrder);
        registerForContextMenu(listView);
        refreshListView();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                Toast.makeText(OrderSheetActivity.this, "MIAM", Toast.LENGTH_LONG).show();

            }
        });


        ImageView logoGoogleMap = (ImageView) findViewById(R.id.logoGoogle);
        logoGoogleMap.setOnClickListener(monListenner);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private ImageView.OnClickListener monListenner = new ImageView.OnClickListener() {
        public void onClick(View v) {
            new GoogleMapManager(getBaseContext()).easyShowOnMap(currentOrder);
        }
    };

    public void editOrderContent(View view) {
        Intent intent = new Intent(this, FormActivity2.class);
        intent.putExtra("orderid", this.currentIdOrder);
        startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        this.setContentView();
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        Window window = getWindow();
        window.setFormat(PixelFormat.RGBA_8888);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.editordercontent, menu);
    }


    @Override
    public boolean onContextItemSelected(MenuItem item) {

        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        ListView listView = (ListView) findViewById(R.id.listViewOrder);

        switch (item.getItemId()) {
            case R.id.button_up:
                ((OrderLine) listView.getItemAtPosition((int) info.id)).addOne();
                refreshListView();
                this.flagOrder = true;
                return true;
            case R.id.button_down:
                ((OrderLine) listView.getItemAtPosition((int) info.id)).removeOne();
                refreshListView();
                this.flagOrder = true;
                return true;
            case R.id.button_delete:
                ((OrderLine) listView.getItemAtPosition((int) info.id)).delete();
                refreshListView();
                this.flagOrder = true;
                return true;
            default:

                return super.onContextItemSelected(item);
        }

    }

    public void actionSave(View view) {
        if (flagOrder == true) {
            SaveTaskSave asyncSaveTask = new SaveTaskSave();
            asyncSaveTask.setContext(this);
            new SyncTaskManager.SendOrder(this).execute(currentOrder);
            asyncSaveTask.execute(this.currentOrder);
        } else {
            actionBackToMain();
        }

    }

    public void actionCancel(View view) {
        this.currentOrder = Order.getOne(this, this.currentIdOrder);
        this.flagOrder = false;
        actionBackToMain();
    }

    private class SaveTaskSave extends Order.saveAsyncSaveTask {
        private SaveTaskSave() {
            super(OrderSheetActivity.this);
        }

        @Override
        protected void onPostExecute(Order order) {
            super.onPostExecute(order);
            OrderSheetActivity.this.flagOrder = false;
            actionBackToMain();
        }
    }

    public void actionBackToMain() {
        finish();
    }

    public void onClickButtonMore(View v) {
        for (OrderLine r : printedOrderLines) {
            if (r.getTag().equals(((Button) v).getTag())) {
                r.addOne();
            }
        }
        refreshListView();
        Toast.makeText(this, "Un de plus !", Toast.LENGTH_SHORT).show();
        this.flagOrder = true;
    }

    public void onClickButtonLess(View v) {
        for (OrderLine r : printedOrderLines) {
            if (r.getTag().equals(((Button) v).getTag())) {
                r.removeOne();
            }
        }
        refreshListView();
        Toast.makeText(this, "Un de moins !", Toast.LENGTH_SHORT).show();
        this.flagOrder = true;
    }

    private void refreshListView() {
        ListView listView = (ListView) findViewById(R.id.listViewOrder);
        updateOrderLines();
        listView.setAdapter(new ListViewOrderSheetAdapter(this, R.layout.listitemordersheet, this.printedOrderLines));

    }

    private void updateOrderLines() {
        try {
            this.printedOrderLines = this.currentOrder.getOrderLines();
        } catch (Exception e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    public void cancelChanges(View view) {
        this.dialog.dismiss();
    }

    public void openDialogPhone(View v) {
        showDialog(CHANGE_PHONE_DIALOG);
    }

    public void openDialogAdress(View v) {
        showDialog(CHANGE_ADRESS_DIALOG);
    }

    public void openDialogName(View view) {
        showDialog(CHANGE_NAME_DIALOG);
    }

    public void saveAdresseChange(View view) {

        EditText editText = (EditText) dialog.findViewById(R.id.editabletextAdresse);
        this.currentOrder.getAddress().setLine1(editText.getText().toString());

        EditText editText1 = (EditText) dialog.findViewById(R.id.editabletextAdresse2);
        this.currentOrder.getAddress().setLine2(editText1.getText().toString());

        EditText editText2 = (EditText) dialog.findViewById(R.id.editabletextAdresseCity);
        this.currentOrder.getAddress().setCity(editText2.getText().toString());

        EditText editText3 = (EditText) dialog.findViewById(R.id.editabletextAdresseCityCode);
        this.currentOrder.getAddress().setPostalCode(editText3.getText().toString());

        this.flagOrder = true;

        this.updateOrderView(this.currentOrder);
        this.dialog.dismiss();
    }

    public void saveNameChanges(View view) {

        String name = ((EditText) dialog.findViewById(R.id.editabletextName)).getText().toString();
        String fisrtname = ((EditText) dialog.findViewById(R.id.editabletextFirstname)).getText().toString();

        this.currentOrder.getClient().setName(name);
        this.currentOrder.getClient().setFirstName(fisrtname);

        this.flagOrder = true;

        this.updateOrderView(this.currentOrder);
        this.dialog.dismiss();
    }

    public void savePhoneChanges(View view) {
        String phoneNumber = ((EditText) dialog.findViewById(R.id.editablePhoneNumber)).getText().toString();

        this.currentOrder.getClient().setPhoneNumber(phoneNumber);

        this.flagOrder = true;

        this.updateOrderView(this.currentOrder);
        this.dialog.dismiss();
    }

    private void updateOrderView(Order order) {


        this.setContentView();

    }

    private Dialog dialog;

    protected Dialog onCreateDialog(int id) {

        switch (id) {
            case CHANGE_ADRESS_DIALOG:

                dialog = new Dialog(OrderSheetActivity.this);
                dialog.setContentView(R.layout.adressedialog);

                EditText editText0 = (EditText) dialog.findViewById(R.id.editabletextAdresse);
                editText0.setText(this.currentOrder.getAddress().getLine1());

                EditText editText10 = (EditText) dialog.findViewById(R.id.editabletextAdresse2);
                editText10.setText(this.currentOrder.getAddress().getLine2());

                EditText editText20 = (EditText) dialog.findViewById(R.id.editabletextAdresseCity);
                editText20.setText(this.currentOrder.getAddress().getCity());

                EditText editText30 = (EditText) dialog.findViewById(R.id.editabletextAdresseCityCode);
                editText30.setText(this.currentOrder.getAddress().getPostalCode());

                dialog.setTitle("Address change");
                ((Button) (dialog.findViewById(R.id.button_save_Adresse))).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        OrderSheetActivity.this.saveAdresseChange(view);
                    }
                });
                ((Button) (dialog.findViewById(R.id.button_save_cancel))).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        OrderSheetActivity.this.cancelChanges(view);
                    }
                });


                break;
            case CHANGE_NAME_DIALOG:

                dialog = new Dialog(OrderSheetActivity.this);
                dialog.setContentView(R.layout.textdialog);
                EditText editText = (EditText) dialog.findViewById(R.id.editabletextName);
                editText.setText("" + this.currentOrder.getClient().getName());
                EditText editText1 = (EditText) dialog.findViewById(R.id.editabletextFirstname);
                editText1.setText("" + this.currentOrder.getClient().getFirstName());
                dialog.setTitle("ClientTable's changes");
                ((dialog.findViewById(R.id.button_save_changes))).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        OrderSheetActivity.this.saveNameChanges(view);
                    }
                });
                ((dialog.findViewById(R.id.button_save_cancel))).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        OrderSheetActivity.this.cancelChanges(view);
                    }
                });

                break;
            case CHANGE_PHONE_DIALOG:

                dialog = new Dialog(OrderSheetActivity.this);
                dialog.setContentView(R.layout.phonenumberdialog);
                EditText editText2 = (EditText) dialog.findViewById(R.id.editablePhoneNumber);
                editText2.setText(this.currentOrder.getClient().getPhoneNumber());
                dialog.setTitle("ClientTable's Phone Number change");
                ((dialog.findViewById(R.id.button_save_Phone_changes))).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        OrderSheetActivity.this.savePhoneChanges(view);
                    }
                });
                ((dialog.findViewById(R.id.button_save_Phone_cancel))).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        OrderSheetActivity.this.cancelChanges(view);
                    }
                });
                break;

            default:
                dialog = null;
        }
        return dialog;
    }

    private void setContentView() {
        try {
            TextView clientName = (TextView) findViewById(R.id.OrderSheetName);
            clientName.setText(this.currentOrder.getClient().getFirstName() + " " + this.currentOrder.getClient().getName());
        } catch (Exception e) {

        }
        try {
            TextView address = (TextView) findViewById(R.id.OrderSheetAddress);
            address.setText(this.currentOrder.getAddress().toString());
        } catch (Exception e) {

        }
        try {
            TextView number = (TextView) findViewById(R.id.OrderSheetNumber);
            number.setText("N°: " + this.currentOrder.getClient().getPhoneNumber());
        } catch (Exception e) {

        }
        try {
            Drawable retroback = getResources().getDrawable(R.drawable.retroback);
            retroback.setAlpha(10);
        } catch (Exception e) {

        }
        try {
            TextView total = (TextView) findViewById(R.id.OrderSheetTotal);
            total.setText(this.currentOrder.getTotalAmountTTC().toString() + "€ (TTC)");
        } catch (Exception e) {

        }

    }
}
